<?php
/**
 * Simple database class
 * Example :
 * $db = Database::getInstance();
 * $db->query("SELECT ...");
 * 
 * @author Matt Pike
 */
class Database{
	private static $instance = null;
	
	
	/**
	 * Actual connection
	 * @var unknown_type
	 */
	private $connection = null;
	/**
	 * Dont instantiate directly, use getInstance() then 
	 */
	private function __construct(){
		$this->connection = mysql_connect(Config::$dbName,Config::$userName,Config::$userPassword);
		if(!$this->connection){
			throw new Exception("Unable to connect to database",93845345);
		}
	}
	/**
	 * Cleanup
	 */
	private function __destruct(){
		mysql_close($this->connection);
	}
	
	
		/**

	 * 
	 * @return Database
	 */
/**
	 * Returns singleton instance of database
	 * 
	 * @return Database
	 */
	public static function getInstance(){
		if(self::$instance){
			return self::$instance;
		}else{
			return new self();
		}
	}
	/**
	 * Basic query function
	 * 
	 * @param string $q
	 */
	public function query($q){
		//Execute query & return result array
		$result = mysql_query($q,$this->connection);
		$rows = mysql_fetch_array($result);
		
		self::__destruct();
		return $rows;
	}
	/**
	 * Call the target SP (WARNING: Params are sent in order of the array!) - Note: See Config.php file for param order & return details!
	 *
	 * @param unknown_type $targetSP
	 * @param array $params
	 * @return array $rows
	 */
	public function callSP($targetSP, array $params){
		
		$q = "CALL ";
		$q .= $targetSP;
		$q .= "(";
		
		//Add params
		//### reset($params); <-- Is this line needed? ###
		while (list($val) = each($params))
		{
  			$q .= $val || ", ";
  		}
  		//Remove additional ','
  		$trimIndex = strrpos($q, ",");
  		$q =substr($q, 0, $trimIndex);
 		//End query construction
  		$q .= ");";
  		
  		//Execute query & cast into result array
  		$result = mysql_query($q,$this->connection);
		//$rows = mysql_fetch_array($result);
		
		//self::__destruct();
  		//return $rows;
  		return $result;
	}
}